"""
日志管理相关路由
"""
import os
from flask import Blueprint, jsonify
from system.logger import Logger

log_bp = Blueprint('logs', __name__, url_prefix='/api/logs')
logger = Logger(root_dir=".", verbose_info=True, verbose_error=True)

@log_bp.route('/recent')
def get_recent_logs():
    """获取最近的日志"""
    try:
        logs = []
        
        # 读取最近的检测日志
        detection_log_path = os.path.join(logger.run_dir, 'detection.log')
        if os.path.exists(detection_log_path):
            with open(detection_log_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                # 获取最后20行
                for line in lines[-20:]:
                    if line.strip():
                        logs.append({'type': 'detection', 'content': line.strip()})
        
        # 读取最近的错误日志
        error_log_path = os.path.join(logger.run_dir, 'error.log')
        if os.path.exists(error_log_path):
            with open(error_log_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()
                for line in lines[-10:]:
                    if line.strip():
                        logs.append({'type': 'error', 'content': line.strip()})
        
        # 按时间排序
        logs.sort(key=lambda x: x['content'][:23] if len(x['content']) > 23 else x['content'], reverse=True)
        
        return jsonify(logs)
    except Exception as e:
        logger.error(f"Failed to get recent logs: {str(e)}")
        return jsonify([]) 